package com.corner.utils;

import android.os.Environment;

import com.corner.app.GlobalParams;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.Thread.UncaughtExceptionHandler;

public class MyCrashHandler implements UncaughtExceptionHandler {

    public static final String MY_LOG_TXT = "MyLog.txt";
    private static MyCrashHandler crashHandler;

    private MyCrashHandler() {
    }

    // 单例
    public static MyCrashHandler instance() {
        if (crashHandler == null) {
//			synchronized (crashHandler) {
            crashHandler = new MyCrashHandler();
//			}
        }
        return crashHandler;
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (crashHandler != null) {
            try {
                // 将crash log写入文件
                FileOutputStream fileOutputStream = new FileOutputStream(
                        new File(Environment.getExternalStorageDirectory(),
                                MY_LOG_TXT), true);
                PrintStream printStream = new PrintStream(fileOutputStream);
                ex.printStackTrace(printStream);
                printStream.append("\n" + GlobalParams.appversion);
                printStream.flush();
                printStream.close();
                fileOutputStream.close();
                AppManager.getInstance().AppExit();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 设置默认处理器
    public void init() {
        Thread.setDefaultUncaughtExceptionHandler(this);
    }
}
